﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Caching;
using System.Collections.Specialized;

namespace ZYStudios.Common
{
    public class FileCacheProvider : OutputCacheProvider
    {

        private DateTime playtimeData = DateTime.MinValue;

        private DateTime indexData = DateTime.MinValue;

        private DateTime index2Data = DateTime.MinValue;

        public FileCacheProvider()
        {
        }

        public override void Initialize(string name, NameValueCollection attributes)
        {
            base.Initialize(name, attributes);
            CachePath = HttpContext.Current.Server.MapPath(attributes["cachePath"]);
            if (!Directory.Exists(CachePath))
            {
                Directory.CreateDirectory(CachePath);
            }
        }

        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            Object obj = Get(key);
            if (obj != null)    //这一步很重要
            {
                return obj;
            }
            Set(key, entry, utcExpiry);
            return entry;
        }

        public override object Get(string key)
        {
            if (key.IndexOf("default/index.html") > -1 || key == "a2/")
            {
                if (indexData.Day != DateTime.Now.Day || indexData.Month != DateTime.Now.Month || indexData.Year != DateTime.Now.Year)
                {
                    indexData = DateTime.Now;
                    return null;
                }
            }

            if (key == "a2/")
            {
                if (index2Data.Day != DateTime.Now.Day || index2Data.Month != DateTime.Now.Month || index2Data.Year != DateTime.Now.Year)
                {
                    index2Data = DateTime.Now;
                    return null;
                }
            }
            

            if (key.IndexOf("playtime.html") > -1)
            {
                if (playtimeData.Day != DateTime.Now.Day || playtimeData.Month != DateTime.Now.Month || playtimeData.Year != DateTime.Now.Year)
                {
                    playtimeData = DateTime.Now;
                    return null;
                }
            }
            string path = ConvertKeyToPath(key);
            if (!File.Exists(path))
            {
                return null;
            }
            CacheItem item = null;
            using (FileStream file = File.OpenRead(path))
            {
                var formatter = new BinaryFormatter();
                item = (CacheItem)formatter.Deserialize(file);
            }

            if (item.ExpiryDate <= DateTime.Now.ToUniversalTime())
            {
                Remove(key);
                return null;
            }
            return item.Item;
        }


        public override void Set(string key, object entry, DateTime utcExpiry)
        {
            CacheItem item = new CacheItem(entry, utcExpiry);
            string path = ConvertKeyToPath(key);
            using (FileStream file = File.OpenWrite(path))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(file, item);
            }
        }

        public override void Remove(string key)
        {
            string path = ConvertKeyToPath(key);
            if (File.Exists(path))
                File.Delete(path);
        }

        public string CachePath
        {
            get;
            set;
        }

        private string ConvertKeyToPath(string key)
        {
            string file = key.Replace('/', '-');
            file += ".txt";
            return Path.Combine(CachePath, file);
        }
    }

    [Serializable]
    public class CacheItem
    {
        public DateTime ExpiryDate;
        public object Item;

        public CacheItem(object entry, DateTime utcExpiry)
        {
            Item = entry;
            ExpiryDate = utcExpiry;
        }
    }
}